package com.tj.jinzao.widgets;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.tj.jinzao.model.Health;
import com.tj.jinzao.model.QueartDataBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LiuYX on 2019/5/13.
 */

public class ChartQView extends View{
    Path mPath;
    Path mShadowPath;
    Paint mPaint;
    Paint mXPaint;//绘制虚线
    Paint mCirlcePaint;
    Paint mOutCirlcePaint;
    private Paint baseShadow;//折线下的阴影的画笔

    public ChartQView(Context context) {
        super(context);
        init();
    }

    public ChartQView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ChartQView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private float sumHeight;//总控件的高度
    private float sumWidth,buttomHeiht=20;//总空间的宽度
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        sumHeight = getMeasuredHeight();
        sumWidth = getMeasuredWidth();

    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private void init(){
        mPath=new Path();
        mShadowPath=new Path();
        mPaint=new Paint();
        mPaint.setStrokeWidth(dip2px(getContext(), 4));
        mPaint.setColor(Color.parseColor("#F5AC30"));
        //设置抗锯齿
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mCirlcePaint=new Paint();
        mCirlcePaint.setStrokeWidth(dip2px(getContext(), 4));
        mCirlcePaint.setColor(Color.parseColor("#FFBA5D"));
        //设置抗锯齿
        mCirlcePaint.setAntiAlias(true);
        mCirlcePaint.setStyle(Paint.Style.FILL);


        mXPaint=new Paint();
        mXPaint.setAntiAlias(true);
        mXPaint.setStyle(Paint.Style.STROKE);
        mXPaint.setColor(Color.parseColor("#F5AC30"));
        mXPaint.setStrokeWidth(dip2px(getContext(), 1));
        PathEffect effects = new DashPathEffect(new float[]{5,5,5,5},1);
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        mXPaint.setPathEffect(effects);


        mOutCirlcePaint=new Paint();
        mOutCirlcePaint.setStrokeWidth(4);
        mOutCirlcePaint.setColor(Color.parseColor("#FFFFFF"));
        //设置抗锯齿
        mOutCirlcePaint.setAntiAlias(true);
        mOutCirlcePaint.setStyle(Paint.Style.FILL);


        baseShadow = new Paint();
        baseShadow.setAntiAlias(true);
        baseShadow.setStyle(Paint.Style.FILL);

    };
    private int minWidth,minHeight,maxWidth,maxHeight,nRadio,oRadio,widthLine;
    public void setInitWH(int minWidth,int minHeight,int maxWidth,int maxHeight,int nRadio,int oRadio,int widthLine){
        this.minWidth=minWidth;
        this.minHeight=minHeight;
        this.maxWidth=maxWidth;
        this.maxHeight=maxHeight;
        this.nRadio=nRadio;
        this.oRadio=oRadio;
        this.widthLine=widthLine;
    }
    List<QueartDataBean> list;
    public void setData(List<QueartDataBean> list){
        this.list=list;
        mPoints=getPoints();
        isStart=true;
        mPath.reset();
        invalidate();
    }
    /**
     * 阴影层叠
     *
     * @param canvas
     * @param Points
     */

    private void drawArea(Canvas canvas, List<PointF> Points) {
        LinearGradient mShader = new LinearGradient(minWidth, minHeight, maxWidth, maxHeight, new int[]{Color.parseColor("#FCEED6"), Color.parseColor("#FFFFFF")}, null, Shader.TileMode.CLAMP);
        baseShadow.setShader(mShader);
        if (Points.size() > 0 && Points != null && Points.size() > 0) {
            mPath.lineTo(Points.get(Points.size() - 1).x, maxHeight);
            mPath.lineTo(Points.get(0).x, maxHeight);
            mPath.close();
            canvas.drawPath(mPath, baseShadow);
        }

    }
    /**
     * 曲线上总点数
     */
    private Point[] mPoints;

    private Point[] getPoints()
    {
        Point[] points = new Point[list.size()];
        for (int i = 0; i < list.size(); i++)
        {
            points[i] = new Point(list.get(i).getStartX(),list.get(i).getStartY());
        }
        return points;
    }
    private List<PointF> getPointsF()
    {
        List<PointF> list1=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            list1.add(new PointF(list.get(i).getStartX(),list.get(i).getStartY()));
        }
        return list1;
    }
    private float smoothness = 0.36f; //折线的弯曲率

    /**
     * 画线
     * 第二种写法，这种根据曲线弯曲率可自由设置，暂时不用
     */
    private void toDrawLine(Canvas canvas) {
        if (list == null || list.size() == 0) {
            return;
        }
        List<PointF> NewPoints = new ArrayList<>();
        NewPoints.addAll(getPointsF());
        float lX = 0;
        float lY = 0;
        mPath = new Path();
        mPath.moveTo(NewPoints.get(0).x, NewPoints.get(0).y);
        for (int i = 1; i < NewPoints.size(); i++) {
            PointF p = NewPoints.get(i);
            PointF firstPointF = NewPoints.get(i - 1);
            float x1 = firstPointF.x + lX;
            float y1 = firstPointF.y + lY;

            PointF secondPointF = NewPoints.get(i + 1 < NewPoints.size() ? i + 1 : i);
            lX = (secondPointF.x - firstPointF.x) / 2 * smoothness;
            lY = (secondPointF.y - firstPointF.y) / 2 * smoothness;
            float x2 = p.x - lX;
            float y2 = p.y - lY;
            if (y1 == p.y) {
                y2 = y1;
            }
            mPath.cubicTo(x1, y1, x2, y2, p.x, p.y);

        }

        canvas.drawPath(mPath, mPaint);
        drawArea(canvas,getPointsF());
    }
    public void setInvidata(){
//        position=0;
        isStart=true;
        mPath.reset();
//        invalidate();

    }
    //点击point的位置
    private int position;


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(list==null||list.size()==0){

        }else {
            for (int i=0;i<list.size();i++){
                if(Math.abs(list.get(i).getStartX()-event.getX())<=20&&Math.abs(list.get(i).getStartY()-event.getY())<=20){
                    position=i;
                    isStart=true;
                    mPath.reset();
//                mXPaint.reset();
                    invalidate();
                    if(onChartClickListener!=null){
                        onChartClickListener.onclick(list.get(i).getId());
                    }
                }
            }

        }
        return super.onTouchEvent(event);
    }
    public void setPosition(int i){
        position=i;
        isStart=true;
        mPath.reset();
        invalidate();

    }
    public interface onChartClickListener{
        void onclick(int id);
    }
    public onChartClickListener onChartClickListener;
    public void setOnChartClickListener(onChartClickListener onChartClickListener){
        this.onChartClickListener=onChartClickListener;
    }

    private void drawScrollLine(Canvas canvas)
    {
        if(list==null||list.size()==0){
            return;
        }
        mPath.moveTo(list.get(0).getStartX(), list.get(0).getStartY());
        if(list!=null&&list.size()>0){
            Point startp = new Point();
            Point endp = new Point();
            for (int i = 0; i < list.size()-1; i++)
            {
                startp = mPoints[i];
                endp = mPoints[i + 1];
                int wt = (startp.x + endp.x) / 2;
                Point p3 = new Point();
                Point p4 = new Point();
                p3.y = startp.y;
                p3.x = wt;
                p4.y = endp.y;
                p4.x = wt;
                mPath.cubicTo(p3.x, p3.y, p4.x, p4.y, endp.x, endp.y);
            }
            canvas.drawPath(mPath, mPaint);
            drawArea(canvas,getPointsF());

        }
    }
    private void drawCircle(Canvas canvas){
        if(list==null||list.size()==0){
            return;
        }

        canvas.drawCircle(list.get(position).getStartX(),list.get(position).getStartY(),oRadio,mOutCirlcePaint);
        canvas.drawCircle(list.get(position).getStartX(),list.get(position).getStartY(),nRadio,mCirlcePaint);
        canvas.drawLine(list.get(position).getStartX(),list.get(position).getStartY(),list.get(position).getStartX(),maxHeight,mXPaint);


    }
    private void clearCanvas(Canvas canvas){
        mPath.reset();
//        //清屏
        Paint paint=new Paint();
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        canvas.drawPaint(paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
        invalidate();


    }
    private boolean isStart=false;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //执行listView时候多次draw导致重绘制（暂时判断一下），之后解决
        if(isStart==false){
            return;
        }
        drawScrollLine(canvas);
        drawCircle(canvas);
        isStart=false;

    }
    private int startX=80,startY=40,endX=640,endY=300;
    private int getWidth(int x){
        return (int) (width/720*x);
    }
    private int getHeight(int y){
        return (int) (height/1280*y);
    }
    float width;
    float height;

    private List<QueartDataBean> list_quart=new ArrayList<>();
    public void initQuart(float width,float height,List<Health> list_h){
        this.width=width;
        this.height=height;
        int sAvg=560/(list_h.size()>15?15:list_h.size());
        if(list_h.size()==1){
            QueartDataBean queartDataBean1=new QueartDataBean();
            queartDataBean1.setStartX(getWidth(startX));
            queartDataBean1.setId(list_h.get(0).getId());
            //2.6=endY-startY/100:平分
            Double d=Double.parseDouble(list_h.get(0).getScores())*2.6;
            int b=d.intValue();
            queartDataBean1.setStartY(getHeight(endY-b));
            queartDataBean1.setReset(false);
            list_quart.add(queartDataBean1);
        }
        for (int i=0;i<(list_h.size()>15?15:list_h.size());i++){
            QueartDataBean queartDataBean1=new QueartDataBean();
            if(i==(list_h.size()>15?14:list_h.size()-1)){
                queartDataBean1.setStartX(getWidth(startX+sAvg*(i+1)));
            }else {
                queartDataBean1.setStartX(getWidth(startX+sAvg*i));
            }
            queartDataBean1.setId(list_h.get(i).getId());
            Double d=Double.parseDouble(list_h.get(i).getScores())*2.6;
            int b=d.intValue();
            queartDataBean1.setStartY(getHeight(endY-b));
            queartDataBean1.setReset(false);
            list_quart.add(queartDataBean1);
        }
        setInitWH(getWidth(startX),getHeight(startY),getWidth(endX),getHeight(endY),getWidth(10),getWidth(12),getWidth(10));
        setData(list_quart);
    }

}
